package com.tcat.user.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tcat.common.enums.ExceptionEnum;
import com.tcat.common.exception.TcatException;
import com.tcat.common.vo.PageResult;
import com.tcat.user.mapper.RoleMapper;
import com.tcat.user.pojo.Roles;
import com.tcat.user.pojo.Users;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
@Service
public class RoleService {
    @Autowired
    private RoleMapper roleMapper;

    public PageResult<Roles> queryRolesByPage(Integer page, Integer rows, String sortBy, Boolean desc, String search) {
        //分页
        PageHelper.startPage(page,rows);
        /*
           WHERE 'name' like '%x%' OR letter =='x'
           ORDER BY id DESC
         */
        //过滤
        Example example=new Example(Roles.class);
        if(StringUtils.isNotBlank(search)){
            example.createCriteria().orLike("name","%"+search+"%");
                    //.orEqualTo("letter",search.toUpperCase());
        }
        //排序
        if(StringUtils.isNotBlank(sortBy)){
            String orderByClause=sortBy +(desc ? " DESC":" ASC");
            example.setOrderByClause(orderByClause);
        }
        //查询
        //分页助手会拦截查询并对他进行分页
        Page<Roles> list = (Page<Roles>)roleMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            throw new TcatException(ExceptionEnum.ROLE_NOT_FOUND);
        }
        //解析分页结果
        PageInfo<Roles> info=new PageInfo<>(list);
        return new PageResult<>(info.getTotal(),list);
    }




    public void deleteByRolesInRps(Long rid) {
        roleMapper.deleteByRolesInRps(rid);
    }
    public void deleteByRolesInUrs(Long rid){
        roleMapper.deleteByRolesInUrs(rid);
    }
    /**
     * 删除品牌  单个（多个删除则每个遍历每个品牌进行删除）
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoles(long id) {
        roleMapper.deleteByPrimaryKey(id);
        deleteByRolesInUrs(id);
        deleteByRolesInRps(id);
    }


    /**
     * 根据品牌id查询角色  用于修改用户信息时，角色信息的回显
     * @param uid
     * @return
     */
    public List<Roles> queryByUserId(Long uid){
        return this.roleMapper.queryByUserId(uid);
    }

    /**
     * 新增角色
     * @param role
     * @param permissions
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveRole(Roles role, List<Long> permissions) {
        //新增品牌
        role.setId(null);
        int count = roleMapper.insert(role);
        if(count!=1){
            throw new TcatException(ExceptionEnum.ROLE_SAVE_ERROR);
        }
        //新增中间表
        for(Long pid:permissions){
            count = roleMapper.insertRps(role.getId(),pid);
            if(count!=1){
                throw  new TcatException((ExceptionEnum.ROLE_SAVE_ERROR));
            }
        }
    }

    /**
     * 角色更新
     * @param role
     * @param permissions
     */
    @Transactional(rollbackFor=Exception.class)
    public void updateRole(Roles role,List<Long> permissions){
        deleteByRolesInRps(role.getId());
        this.roleMapper.updateByPrimaryKeySelective(role);
        for(Long pid:permissions){
            this.roleMapper.insertRps(role.getId(),pid);
        }
    }

    /**
     * 查询所有角色
     * @return
     */
    public List<Roles> queryAll(){
        return roleMapper.selectAll();
    }


}
